package com.waimai.app.qa.tool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * IOProcessor,对文件的输入输出进行处理
 * @author AiHui
 *
 */
public class IOProcessor{
	/**
	 * 将text文本写入都outFileName文件中
	 * @param text
	 * @param outFileName
	 */
	public void writeToFile(String text, String outFileName){
		try{
			FileOutputStream buf = new FileOutputStream(new File(outFileName), false);
			Writer out = new OutputStreamWriter(buf);
			out.write(text);
			out.close();
		}
		catch (Exception e){
			e.printStackTrace();
			return;
		}
	}
	
   /**
    * 从文件inFileName（csv文件）中读入数据，其中csv文件中的itemName作为key，type、testData、locatorValue整体作为value，解析后存入map集合中。
    * @param inFileName
    * @return
    */
	public Map<String,String> readNameFromFile(String inFileName){
		File inFile = new File(inFileName);
		FileInputStream fis = null;
		
		try{
			fis = new FileInputStream(inFile);
		}
		catch (FileNotFoundException e){
			e.printStackTrace();
		}
		
		BufferedReader in = new BufferedReader(new InputStreamReader(fis));
		Map map=new HashMap();
		String thisLine;
		
		try{
			while ((thisLine = in.readLine()) != null) {    
				thisLine = thisLine.trim();
				if (!thisLine.equals("")&&!thisLine.startsWith("#")){   
				   //以|作为分界线分隔文件的每一行
					String varName = thisLine.split("\\|")[0].trim();
					//首行数据不需要解析，跳过
					if(varName.equals("elementName")){
						continue;
					}
					
					//将type，testData、locatorValue分别作为解析后形成一个整体作为value 
					String data = thisLine.split("\\|")[1].trim();
                    String typeName = thisLine.split("\\|")[2].trim();
					String locator = thisLine.split("\\|")[3].trim();
					String attr=typeName+"|"+data+"|"+locator;
					if (!varName.equals(""))
						map.put(varName, attr);
				}
			}
		}
		catch (IOException e){
			e.printStackTrace();
		}
		return map;
	}
	
   /**
    * 从dir文件夹中筛选出csv文件并获取文件名存入到一个String数组中。
    * @param dir
    * @return
    */
	public String[] listFilesName(String dir){
		File directory = new File(dir);
		File files[] = directory.listFiles(new ExtensionFileFilter("csv"));
		int j = files.length;
		//System.out.println(j);
		String fs[] = new String[j];
		for (int i = 0; i < j; i++)
			if (files[i].isFile())
				fs[i] = files[i].getName();
		return fs;
	}
}
